package com.czh.wx.handler;

import com.czh.wx.constants.WxConstant;
import com.czh.wx.redis.RedisUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author caozaihui
 * @version 1.0
 * @since 2024/9/1 下午 9:25
 */
@Component
@Slf4j
public class ReceiveTextMsgHandler implements WxMsgHandler{

    @Resource
    private RedisUtil redisUtil;
    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String,String> requestMap) {
        String toUserName = requestMap.get(WxConstant.XMLNODE_ToUserName);
        String fromUserName = requestMap.get(WxConstant.XMLNODE_FromUserName);
        String content = requestMap.get(WxConstant.XMLNODE_Content);
        String responseMsg ;
        log.info("用户发送了文本信息:{}", content);
        if (content.equals(WxConstant.CAPTCHA)){
            Object oldCaptcha = redisUtil.getCacheObject(fromUserName);
            if (Objects.isNull(oldCaptcha)){
                Random random = new Random();
                int code = random.nextInt(1000,10000);
                responseMsg = "您的验证码是："+code;
                redisUtil.setCacheObject(redisUtil.buildKey(WxConstant.REDIS_CAPTCHA_KEY, String.valueOf(code)),fromUserName,WxConstant.REDIS_CAPTCHA_EXPIRE, TimeUnit.MINUTES);
                redisUtil.setCacheObject(fromUserName,WxConstant.CAPTCHA,WxConstant.REDIS_CAPTCHA_CONFINE,TimeUnit.MINUTES);
                log.info("用户{}获取验证码:{}", fromUserName, code);
            }else {
                log.info("{}用户{}一分钟内重复获取验证码", fromUserName, fromUserName);
                responseMsg = "一分钟后重新获取验证码";
            }
        }else {
            responseMsg  = "你好!你准备干嘛?";
        }
        return "<xml>\n" +
                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "  <CreateTime>1348831860</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA["+responseMsg+"]]></Content>\n" +
                "  <MsgId>1234567890123456</MsgId>\n" +
                "  <MsgDataId>xxxx</MsgDataId>\n" +
                "  <Idx>xxxx</Idx>\n" +
                "</xml>";
    }
}
